package br.com.dojo.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.FlushModeType;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
 
@SuppressWarnings("unchecked")
@Repository
public class DAOGenerico<PK, T> {
	
	@PersistenceContext
	private EntityManager entityManager;
	
    public DAOGenerico() {
    }
    
    public void flush(){
        entityManager.flush();
    }
    
    public void setFlushMode(FlushModeType type){
        entityManager.setFlushMode(type);
    }
 
    public T getById(PK pk) {
        return (T) entityManager.find(getTypeClass(), pk);
    }
 
    public T getByIdLazy(PK pk) {
        return (T) entityManager.getReference(getTypeClass(), pk);
    }
    
    public void save(T entity) {
    	//entityManager.getTransaction().begin();
        entityManager.persist(entity);
        //entityManager.getTransaction().commit();;
//        entityManager.close();
    }
 
    public void update(T entity) {
        entityManager.merge(entity);
    }
 
    public void delete(PK pk) {
        T entity = this.getById(pk);
        entityManager.remove(entity);
    }
 
    public List<T> findAll() {
    	return entityManager.createQuery("FROM " + getTypeClass().getName())
    			.getResultList();
    }
    
    private Class<?> getTypeClass() {
        Class<?> clazz = (Class<?>) (
                (ParameterizedType) this.getClass()
                .getGenericSuperclass())
                .getActualTypeArguments()[1];
        return clazz;
    }
}